// src/stores/auth.js - 简化的认证状态管理
import { defineStore } from 'pinia'
import { ref } from 'vue'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'

export const useAuthStore = defineStore('auth', () => {
  const isLoggedIn = ref(false)
  const user = ref(null)
  const token = ref(null)

  // 初始化时检查本地存储
  const initAuth = () => {
    const savedToken = localStorage.getItem('auth_token')
    const savedUser = localStorage.getItem('user_data')

    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
      isLoggedIn.value = true
    }
  }

  // 登录
  const login = async (username, password) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/v1/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      })

      const data = await response.json()

      if (response.ok) {
        // 保存认证信息
        token.value = data.access_token || data.token
        user.value = {
          id: data.user?.id || Date.now(),
          username: data.user?.username || username,
          name: data.user?.name || username
        }
        isLoggedIn.value = true

        // 持久化
        localStorage.setItem('auth_token', token.value)
        localStorage.setItem('user_data', JSON.stringify(user.value))

        return { success: true, message: '登录成功' }
      }

      return { success: false, message: data.message || '登录失败' }
    } catch (error) {
      console.error('登录错误:', error)
      return { success: false, message: '网络错误' }
    }
  }

  // 注册
  const register = async (username, email, password) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/v1/auth/register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, email, password })
      })

      const data = await response.json()

      if (response.ok) {
        return { success: true, message: '注册成功，请登录' }
      }

      return { success: false, message: data.message || '注册失败' }
    } catch (error) {
      console.error('注册错误:', error)
      return { success: false, message: '网络错误' }
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = null
    isLoggedIn.value = false
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_data')
  }

  // 检查认证
  const checkAuth = () => {
    return isLoggedIn.value
  }

  // 初始化
  initAuth()

  return {
    isLoggedIn,
    user,
    token,
    login,
    register,
    logout,
    checkAuth
  }
})